package com.grant.code.service.impl;

import com.grant.code.exception.AuthException;
import com.grant.code.mapper.UserMapper;
import com.grant.code.pojo.User;
import com.grant.code.service.UserService;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(User user) {
        User dbUser = userMapper.getByUserName(user.getUserName().trim());
        if (dbUser == null) {
            throw new AuthException("用户不存在");
        }
        if (!Objects.equals(dbUser.getUserPassword(), user.getUserPassword())){
            throw new AuthException("密码错误");
        }
        log.info("数据库用户{}", dbUser);
        log.info("数据库密码{}", dbUser.getUserPassword());
        log.info("用户输入密码{}", user.getUserPassword());
        if (dbUser == null) {
            throw new AuthException("用户不存在");
        }
        if (!Objects.equals(dbUser.getUserPassword(), user.getUserPassword())){
            throw new AuthException("密码错误");
        }
        return dbUser;
    }

    @Override
    public boolean checkUserExist(String username) {
        return userMapper.getByUserName(username) != null;
    }

    /**
     * 注册
     * @param user
     * @throws SQLException
     */
    @Transactional
    @Override
    public void register(User user) {
        if (checkUserExist(user.getUserName())) {
            throw new RuntimeException("用户已存在");
        }
        //设置入职时间为当前时间 格式化yyyy-MM-dd
        user.setUserHiredate(LocalDate.now().toString());
        user.setUserStatus("0");
        user.setUserRole("student");
        userMapper.register(user);
    }

    @Override
    public void updateUserAvatar(Integer userId, String avatarPath) {
        userMapper.updateUserAvatar(userId, avatarPath);
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    public void updateUser(User updatedUser) {
        String userHiredate = updatedUser.getUserHiredate();
        if (!isValidDate(userHiredate)){
            throw new IllegalArgumentException("非法的入职日期格式");
        }
        userMapper.updateUser(updatedUser);
    }

    private boolean isValidDate(String dateStr) {
        try {
            LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }
}
